/*-----------------------------------------------------
 * Html编辑器与MarkDown编辑器切换组件
 * ---------------------------------------------------*/
jx.switchHtmlMarkdownEditor = function () {
    //私有变量
    var $tabs, $tabContent, $content, htmlOps, mdOps;
    var htmlInstance, mdInstance, currentContent, currentFormat;
    var htmlId = 'html_kindeditor_content_id', mdId = 'md_editormd_content_id';
    var turndownService = new TurndownService({
        headingStyle: "atx",
        hr: "- - -",
        bulletListMarker: "-",
        codeBlockStyle: "fenced"
    });
    turndownService.use(turndownPluginGfm.gfm);

    var sdown = new showdown.Converter;
    sdown.setOption("strikethrough", true);
    sdown.setOption("tables", true);
    sdown.setOption("smartIndentationFix", true);
    sdown.setOption("omitExtraWLInCodeBlocks", true);

    var md_mini = ["undo", "redo", "|", "bold", "italic", "hr", "|", "quote", "list-ul", "list-ol", "|", "link", "image", "code", "|", "preview", "watch", "||", "fullscreen"];
    var md_full = ["undo", "redo", "|", "bold", "italic", "del", "quote", "ucwords", "uppercase", "lowercase", "|", "h1", "h2", "h3", "h4", "h5", "h6", "|", "list-ul", "list-ol", "hr", "|", "link", "reference-link", "image", "code", "code-block", "table", "datetime", "html-entities", "pagebreak", "|", "goto-line", "clear", "|", "preview", "watch", "||", "fullscreen"];

    //私有方法

    var kindeditorInit = function () {
        var $editor = $('<textarea id="' + htmlId + '" class="jx-hide"></textarea>');
        $tabContent.append($editor);
        htmlInstance = $editor.jxhtmleditor($.extend({}, htmlOps));
        htmlInstance.getEditor().html(currentContent);
    };
    var kindeditorGetMarkdown = function () {
        if (htmlInstance) {
            return turndownService.turndown(htmlInstance.getEditor().html());
        }
        return $content.val();
    };
    var kindeditorDestroy = function () {
        if (htmlInstance) {
            var $editor = $(htmlInstance.getElement());
            KindEditor.remove($editor.selector);
            $editor.removeData('jxhtmleditor');
            $tabContent.empty();
            htmlInstance = null;
        }
    };

    var markdownInit = function () {
        var $editor = $('<div id="' + mdId + '"></div>');
        $tabContent.append($editor);
        mdInstance = $editor.jxmdeditor($.extend({}, {
            markdown: currentContent,
            syncScrolling: true,
            toc: false,
            tex: false,
            emoji: false,
            watch: false,
            pageBreak: true,
            lineNumbers: false,
            saveHTMLToTextarea: false,
            previewTheme: "osc",
            autoFocus: true,
            imageUpload: true,
            matchWordHighlight: false,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            toolbarIcons: function () {
                return md_mini;
            },
            onfullscreen: function () {
                this.cm.setOption("lineNumbers", true);
                this.codeMirror.find(".CodeMirror-gutters").css("border-right", "1px solid #ddd;");
                this.settings.toolbarIcons = function () {
                    return md_full;
                }
                this.setToolbar();
                this.watch();
                this.resize();
                this.focus();
            },
            onfullscreenExit: function () {
                this.cm.setOption("lineNumbers", false);
                this.codeMirror.find(".CodeMirror-gutters").css("border-right", "none");
                this.settings.toolbarIcons = function () {
                    return md_mini;
                };
                this.setToolbar();
                this.unwatch();
                this.resize();
                this.focus();
            },
            // onload: function () {
            //     this.cm.on("change", function () {
            //         $content.val(ui.markdownEditorInstance.getMarkdown());
            //     });
            // }
        }, mdOps));
    };
    var markdownGetHTML = function () {
        if (mdInstance) {
            var md = mdInstance.getEditor().getMarkdown();
            return sdown.makeHtml(md);
        }
        return $content.val();
    };
    var markdownDestroy = function () {
        if (mdInstance) {
            var $editor = $(mdInstance.getElement());
            mdInstance.getEditor().editor.remove();
            $editor.removeData('jxmdeditor');
            $tabContent.empty();
            mdInstance = null;
        }
    };

    var switchEditor = function (format) {
        KindEditor.ready(function () {
            if (format == '1') { //html
                currentContent = markdownGetHTML();
                markdownDestroy();
                kindeditorInit();
            }
            else if (format == '2') { //md
                currentContent = kindeditorGetMarkdown();
                kindeditorDestroy();
                markdownInit();
            }
            var $item = $tabs.find('a[data-format="' + format + '"]');
            $item.closest('ul').find('li').removeClass('active');
            $item.parent().addClass('active');
            currentFormat = format;
        });
    };
    var bingClick = function () {
        $tabs.find('ul>li>a').click(function () {
            var currentFormat = $tabs.find('ul>li.active>a').data('format');
            var $this = $(this);
            var format = $this.data('format');
            if (currentFormat == format) {
                return;
            }
            switchEditor(format);
        });
    };

    //公共方法
    return {
        init: function (_$tabs, _$content, _format, _htmlOps, _mdOps) {
            $tabs = _$tabs;
            $tabContent = _$tabs.find('.tab-content>div');
            $content = _$content;
            htmlOps = _htmlOps;
            mdOps = _mdOps;
            bingClick();
            switchEditor(_format);
        },
        getContent: function () {
            if (currentFormat == '1') { //html
                return htmlInstance.getEditor().html();
            }
            else if (currentFormat == '2') { //md
                return mdInstance.getEditor().getMarkdown();
            }
        },
        getFormat: function () {
            return currentFormat;
        }
    };
}();